<?php
/**
 * User: lsx
 * Date: 2017/6/2
 * Time: 10:32
 * Progress:0%
 */

namespace logic\admin\shop;


use model\ShopGoods;
use model\ShopGoodsCategory;
use model\ShopGoodsVariant;
use model\ShopUserGroup;
use think\Db;

class LShopGoods
{
    private $shopGoods;
    private $shopGoodsCategory;
    private $shopUserGroup;
    private $shopGoodsVarant;

    public function __construct()
    {
        $this->shopGoods = new ShopGoods();
        $this->shopGoodsCategory = new ShopGoodsCategory();
        $this->shopGoodsVarant = new ShopGoodsVariant();
        $this->shopUserGroup = new ShopUserGroup();
    }

    public function logic_index($param)
    {
        $store_id = $param['store_id'];
        //只查询对应店铺的商品
        if (!empty($store_id)) {
            //上架
            $cal['up'] = $this->shopGoods->where(['flag_putaway' => 1, 'store_id' => $store_id])->count();
            //下架
            $cal['down'] = $this->shopGoods->where(['flag_putaway' => 0, 'store_id' => $store_id])->count();
            $cal['sales'] = $this->shopGoods->where(['store_id' => $store_id])->sum('sales');
            $cal['sales_real'] = $this->shopGoods->where(['store_id' => $store_id])->sum('sales_real');
        } else {
            //上架
            $cal['up'] = $this->shopGoods->where(['flag_putaway' => 1])->count();
            //下架
            $cal['down'] = $this->shopGoods->where(['flag_putaway' => 0])->count();
            $cal['sales'] = $this->shopGoods->sum('sales');
            $cal['sales_real'] = $this->shopGoods->sum('sales_real');
        }

        return $cal;
    }

    public function logic_index_data($param)
    {
        $where = array();
        $keywords = $param['search'];
        if (!empty($keywords)) {
            $where['name'] = array('like', "%{$keywords}%"); //查询条件
        }
        if ($param['flag_putaway'] > 0 or $param['flag_putaway'] == 0) {
            $where['flag_putaway'] = $param['flag_putaway']; //查询条件
        }
        $where['flag_delete'] = 0;

        $store_id = $param['store_id'];
        if($store_id> 0){
            $where['store_id'] = $store_id; //只查询对应店铺的商品
        }

        $page_size = $param['limit']; //获取分页数
        $start = $param['offset']; //获取开始的记录数
        //获取排序字段------------------------------------------------------------开始

        $sort_name = $param['sort'];
        $sort_desc = $param['order'];

        if (!empty($sort_name)) {
            $sort[$sort_name] = $sort_desc;
        } else {
            $sort['flag_putaway'] = 'desc'; //默认排序
            $sort['add_time'] = 'desc'; //默认排序
        }
        //获取排序字段------------------------------------------------------------结束

        $total = $this->shopGoods->where($where)->count();
        $rows = $this->shopGoods
            ->with('ShopStore')
            ->where($where)
            ->limit($start, $page_size)
            ->order($sort)
            ->select();

        foreach ($rows as &$row) {
            $row['cate_name'] = $this->format_category($row['category_tree']);;
            $row['variant_name'] = $this->format_variant($row["id"]);
            $row['flag_putaway'] = show_status($row['flag_putaway'],$row["id"]);
        }
        return array(
            'total' => $total,
            'rows' => $rows
        );
    }

//    public function logic_level($id=null){
//        $data_arr=$this->shopUserGroup->select();
////        $data_arr=$data->toArray();
//        if($id){
//            foreach ($data_arr as &$item) {
//                $price=$this->shopGoodsGroupPrice->where(['group_id'=>$item['id'],'goods_id'=>$id])->value('price');
//                $item['price']=$price;
//            }
//        }
//        return $data_arr;
//    }

    public function logic_insert($params1,$params2)
    {
        Db::startTrans();
        try{
            $this->shopGoods->save($params1);
            $goods_id = $this->shopGoods->id;
            //
            if($goods_id > 0 && !empty($params2['variant_name'][0])){
                foreach ($params2['variant_name'] as $key => $value){
                    $data[$key]['goods_id'] = $goods_id;
                    $data[$key]['name'] = $value;
                }
                foreach ($params2['variant_price'] as $key => $value){
                    $data[$key]['price'] = $value;
                }

                $ShopGoodsVariant=new ShopGoodsVariant();
                foreach ($data as $key => $value){
                    $ShopGoodsVariant->insert($value);
                }
            }

            $ret =[
                'success' => true,
                'message' => '添加成功'
                ];

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $ret =[
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
        return $ret;
    }

    public function logic_edit($id)
    {
        $data = $this->shopGoods->where(['id' => $id])->find();
        return $data->getData();
    }

    public function logic_update($params1,$params2)
    {
        Db::startTrans();
        try{
            $goods_id = $params1['id'];
            $deleted_variant_ids = $params2['deleted_variant_ids'];

            //更新商品信息
            $this->shopGoods->save($params1,['id' => $goods_id]);

            $ShopGoodsVariant=new ShopGoodsVariant();
            //删除要删除的数据
            if(!empty($deleted_variant_ids)){
                $ShopGoodsVariant->where('id','in',$deleted_variant_ids)->update(['flag_delete'=>1]);
            }

            //组织更新或新增的数据
            if(!empty($params2['variant_name'][0])){

                foreach ($params2['variant_name'] as $key => $value){
                    $data[$key]['goods_id'] = $goods_id;
                    $data[$key]['name'] = $value;
                }
                foreach ($params2['variant_price'] as $key => $value){
                    $data[$key]['price'] = $value;
                }

                if($params2['variant_id']){
                    foreach ($params2['variant_id'] as $key => $value){
                        $data[$key]['id'] = $value;
                    }
                }

                $ShopGoodsVariant->saveAll($data);

            }

            $ret =[
                'success' => true,
                'message' => '编辑成功'
            ];

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $ret =[
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
        return $ret;
    }

    public function logic_delete($id)
    {
        Db::startTrans();
        $res = $this->shopGoods->where(['id' => $id])->setField(["flag_delete" => 1]);
        if (!$res) {
            Db::rollback();
            return array(
                'success' => false,
                'message' => '删除失败'
            );
        }

        Db::commit();
        return array(
            'success' => true,
            'message' => '删除成功'
        );
    }

    public function logic_cates($id)
    {
        $item = $this->shopGoods->where(['id' => $id])->value('category_tree');
        if (strstr($item, ",") == false) {
            $cate_arr = array($item);
        } else {
            $cate_arr = explode(',', $item);
        }
        return $cate_arr;

    }

    public function logic_category()
    {

    }

    /**
     * 查询指定店铺下的所有商品分类信息
     * @param int $store_id 店铺ID
     * @return false|mixed|string
     */
    protected function logic_get_category($store_id)
    {
        $where['flag_delete'] = 0;
        $where['store_id'] = $store_id;
        $data = Db::name('shop_goods_category')->where($where)->field('id,name')->select();

        return $data;
    }

    function get_top_parentid($id, $ids = array())
    {
        $r = $this->shopGoodsCategory->where(['id' => $id])->find();
        if ($r) {
            $ids[] = $r->getData()['id'];
            if ($r->getData()['parent_id'] != '0') {
                return $this->get_top_parentid($r['parent_id'], $ids);
            }
        }
        return $ids;
    }

    /**
     * 格式化商品分类样式
     * @param string $category_id 分类ID
     * @param string $store_id 店铺ID
     * @return string
     */
    protected function format_category($category_id){
        $category_name = $this->shopGoodsCategory->where(['id' => $category_id,'flag_delete'=>0])->value('name');
        $categoryHtml = '<button style="margin-right: 5px" class="btn btn-default btn-xs" href="javascript:void(0)">' . $category_name . '</button>';
        return $categoryHtml;
    }

    /**
     * 格式化商品规格样式
     * @param int $goods_id 商品ID
     * @return string
     */
    protected function format_variant($goods_id){
        $variantHtml = "";
        $variant = $this->shopGoodsVarant->where(["goods_id" => $goods_id,'flag_delete'=>0])->field("id,name,price")->select();
        foreach ($variant as $item) {
            $variantHtml .= '<button style="margin-right: 5px" class="btn btn-default btn-xs ud-btn-variant" href="javascript:void(0)" data-variantId="' . $item["id"] .'">' . $item["name"] . " ￥" . $item["price"] . '</button>';
        }
        return $variantHtml;
    }

}